<?php

namespace app\store\controller;

use app\admin\common\Base;
use think\Db;

use app\store\model\CostOrder as Model;
use app\store\model\CostOrderDetails as ModelDetails;

//成本调整单
class Costadjustment extends Base
{
    public function index()
    {
        $data = $this->request->param();
        if (isset($data['ajax']) && $data['ajax'] == 100) {
            $map = '';
            $page = isset($data['page']) ? $data['page'] : 1;
            $page = intval($page);
            $limit = isset($data['rows']) ? $data['rows'] : 10;
            $limit = intval($limit);
            $start = $limit * ($page - 1);

            if (isset($data['search'])) {

                $sql = Db('cost_order')->where('is_del',0)->where('enterprise_id',$this->EnterpriseId);
                $sql = empty($data['matchCon']) ? $sql : $sql->where('sn|mark','like','%'.$data['matchCon'].'%');
                $sql = empty($data['startdate']) ?$sql : $sql->where('addtime','between',[$data['startdate'],$data['enddate']]);
                $list = $sql->select();
                $count = sizeof($list);
                
            }else{
                
                if ($map == '') {
                $list = Db::name('cost_order')->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->order('id asc')->limit($start, $limit)->select();
                $count = Db::name('cost_order')->where('enterprise_id', $this->EnterpriseId)->where('is_del', 0)->count();
                } else {
                    $list = Db::name('cost_order')->where('is_del', 0)->order('id asc')->where('enterprise_id', $this->EnterpriseId)->limit($start, $limit)->select();
                    $count = Db::name('cost_order')->where('enterprise_id', $this->EnterpriseId)->where('is_del', 0)->count();
                }
            }

            foreach ($list as $k => &$v) {
                $v['addtime'] = date('Y-m-d', $v['addtime']);
                if ($v['type'] == 0)
                    $v['type'] = '成本调整';
                $v['money'] = Db::name('cost_order_details')->where('pid', $v['id'])->where(['is_del' => 0, 'enterprise_id' => $this->EnterpriseId])->sum('money');
                $v['auth_user'] = Db::name('auth_user')->where('id', $v['by_id'])->value('name');
            }

            return $this->grid_data($list, $count, $page, $limit);
        }

        return $this->fetch();
    }

    public function add()
    {
        $sn = osn('CBTZ', 4);
        $store = Db::name('store')->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->where('status', 0)->order('sort desc,id desc')->select();
        $this->assign('sn', $sn);
        $this->assign('store', $store);
        $this->assign('admin', $this->Userinfo);
        return $this->fetch();
    }

    //编辑栏目1-1
    public function edit($id)
    {
        $data = $this->request->param();

        if (isset($data['ajax']) && $data['ajax'] == 100) {

            $page = isset($data['page']) ? $data['page'] : 1;
            $page = intval($page);
            $limit = isset($data['rows']) ? $data['rows'] : 10;
            $limit = intval($limit);
            $start = $limit * ($page - 1);

            $list = Db::name('cost_order_details')->where('pid', $data['id'])->where('is_del', 0)->select();
            $count = Db::name('cost_order_details')->where('pid', $data['id'])->where('is_del', 0)->count();

            $ii=0;
            foreach ($list as $key => &$value) {
                $value['o_id'] = $value['id'];
                $goods = Db::name('goods')->where('id', $value['goods_id'])->find();
                $list[$key]['goods_id'] = $goods['id'];
                $list[$key]['goodsname'] = $goods['sn'] . ' ' . $goods['name'];
                $list[$key]['mark'] = $value['mark'];
                $unit = Db::name('unit')->where('id', $value['unit_id'])->find();
                $list[$key]['unit_id'] = $unit['id'];
                $list[$key]['dw_name'] = $unit['name'];
                $store = Db::name('store')->where('id', $value['store_id'])->find();
                $list[$key]['store_id'] = $store['id'];
                $list[$key]['locationName'] = $store['name'];
                $value['id']=$ii+1;
                $ii+=1;
            }

            //少于5条则填充
            if (5 - $count > 0) {
                for ($i = 0; $i < 5 - $count; $i++) {
                    array_push($list, ['id'=>$count+$i+1]);
                }
            }

            return $this->grid_data($list, $count, $page, $limit);
        }
        $info = Db::name('cost_order')->where('id', $data['id'])->find();
        // 处理数据
        $info['addtime'] = date('Y-m-d', $info['addtime']);
        $store = Db::name('store')->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->where('status', 0)->order('sort desc,id desc')->select();
        $info['by_name'] = Db::name('auth_user')->where('id', $info['by_id'])->value('name');
        $info['editby_name'] = Db::name('auth_user')->where('id', $info['editby_id'])->value('name');
        $info['edittime'] = $info['edittime'] != 0 ? date('Y-m-d H:i:s', $info['edittime']) : '';

        $this->assign('store', $store);
        $this->assign('id', $id);
        $this->assign('info', $info);
        $this->assign('admin', $this->Userinfo);

        return $this->fetch();
    }

    public function save()
    {
        $data = $this->request->param();

        $details = $data['movedata'];
        unset($data['movedata']);
        $data['addtime'] = strtotime($data['addtime']);
        $data['by_id'] = $this->Userinfo['id'];
        $data['enterprise_id'] = $this->EnterpriseId;
        $model = new Model();
        Db::startTrans();
        $res = $model->allowField(true)->save($data);
        if (!$res) {
            Db::rollback();
            return json(['status' => 0, 'msg' => '操作失败']);
        }

        foreach ($details as $key => $value) {
            $details[$key]['pid'] = $model->id;
            $details[$key]['enterprise_id'] = $this->EnterpriseId;
        }

        $modelDetails = new ModelDetails;
        $result = $modelDetails->allowField(true)->saveAll($details);
        if (!$result) {
            Db::rollback();
            return json(['status' => 0, 'msg' => '操作失败']);
        }

        Db::commit();
        return json(['status' => 1, 'msg' => '添加成功']);
    }

    public function update()
    {
        $data = $this->request->param();
        $details = $data['movedata'];
        unset($data['movedata']);
        $data['updatetime'] = time();
        $data['edittime'] = time();
        $data['editby_id'] = $this->Userinfo['id'];
        $data['enterprise_id'] = $this->EnterpriseId;
        $data['addtime'] = strtotime($data['addtime']);
        $model = new Model();
        Db::startTrans();
        $res = $model->allowField(true)->save($data, ['id' => $data['id']]);
        if (!$res) {
            Db::rollback();
            return json(['status' => 0, 'msg' => '操作失败']);
        }
        // 先删除，后添加
        $delres = Db::name('cost_order_details')->where('pid', $data['id'])->update(['is_del' => 1]);
        if (!$delres) {
            Db::rollback();
            return json(['status' => 0, 'msg' => '操作失败，删除原有数据失败']);
        }
        foreach ($details as $key => $value) {
            $details[$key]['pid'] = $model->id;
            $details[$key]['enterprise_id'] = $this->EnterpriseId;
        }

        $modelDetails = new ModelDetails;
        $result = $modelDetails->allowField(true)->saveAll($details);
        if (!$result) {
            Db::rollback();
            return json(['status' => 0, 'msg' => '操作失败']);
        }

        Db::commit();
        return json(['status' => 1, 'msg' => '添加成功']);
    }

    public function del()
    {
        $data = $this->request->param();
        $del = del('cost_order', $data['id']);
        if ($del) {
            return json(['status' => 1, 'msg' => '删除成功']);
        } else {
            return json(['status' => 1, 'msg' => '删除成功']);
        }
    }

    public function shenhe()
    {
        $data = $this->request->param();
        $status = 0;
        $msg = "操作失败";
        $id = $data['id'];
        $type = $data['type'];
        // 启动事务
        Db::startTrans();
        $info = Db::name('stock_record')->where('id', $id)->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->find();
        //if($info['xhdd_id']==0&&$info['xht_id']==0&&$info['xh_id']==0){
        if ($type == 1) {
            $update = [
                'status' => 1,
                'updatetime' => time(),
                'shenhe_time' => time(),
                'shenhe_user' => $this->Userinfo['id'],
                'last_user' => $this->Userinfo['id'],
            ];
            $result = Db::name('stock_record')->where('id', $id)->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->update($update);
        }
        if ($type == 2) {
            $update = [
                'status' => 0,
                'updatetime' => time(),
                'shenhe_time' => 0,
                'shenhe_user' => 0,
                'last_user' => $this->Userinfo['id'],
            ];
            $result = Db::name('stock_record')->where('id', $id)->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->update($update);
        }
        if ($result) {
            // 提交事务
            Db::commit();
            $status = 1;
            $msg = "操作成功";
        }
        // }else{
        //     $msg="存在关联单据不能操作";
        // }
        if ($status != 1) {
            // 回滚事务
            Db::rollback();
        }
        return ['status' => $status, 'msg' => $msg];
    }

    public function details()
    {
        $data = $this->request->param();
        $oid = $data['record_id'];
        $o = Db::name('stock_record')->where('id', $oid)->where('is_del', 0)->find();
        $customer = Db::name('customer')->where('id', $o['user_id'])->find();
        $o['customer_name'] = $customer['sn'] . ' ' . $customer['name'];

        //halt($o);
        if (isset($data['ajax']) && $data['ajax'] == 100) {
            $map = '';
            $page = isset($data['page']) ? $data['page'] : 1;
            $page = intval($page);
            $limit = isset($data['rows']) ? $data['rows'] : 10;
            $limit = intval($limit);
            $start = $limit * ($page - 1);

            if ($map == '') {
                $list = Db::name('stock_record_good')->where('pid', $oid)->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->order('addtime desc,id asc')->limit($start, $limit)->select();
                $count = Db::name('stock_record_good')->where('pid', $oid)->where('enterprise_id', $this->EnterpriseId)->where('is_del', 0)->count();
            } else {
                $list = Db::name('stock_record_good')->where('pid', $oid)->where('is_del', 0)->order('sort desc,id asc')->where('enterprise_id', $this->EnterpriseId)->limit($start, $limit)->select();
                $count = Db::name('stock_record_good')->where('pid', $oid)->where('enterprise_id', $this->EnterpriseId)->where('is_del', 0)->count();
            }

            foreach ($list as $key => &$val) {
                $g = Db::name('goods')->where('id', $val['good_id'])->find(); //商品
                $c = Db::name('store')->where('id', $val['store_id'])->find(); //仓库
                $val['goodsname'] = $g['name'];
                $val['dw'] = Db::name('unit')->where('id', $val['unit_id'])->value('name'); //仓库
                $val['store_name'] = $c['name'];
            }
            //少于5条则填充
            if (5 - $count > 0) {
                for ($i = 0; $i < 5 - $count; $i++) {
                    array_push($list, []);
                }
            }
            return $this->grid_data($list, $count, $page, $limit);
        }


        //仓库
        $store = Db::name('store')->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->order('sort desc,id desc')->select();
        $this->assign('store', $store);
        $this->assign('info', $o);
        return $this->fetch();
    }
}
